using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Abp.Auditing;
using Abp.Domain.Entities.Auditing;
using Abp.UI;
using L._52ABP.Application.Dtos;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Yozeev.AppFolders;
using Yozeev.BusinessLogic.Common.Dtos;
using Yozeev.DataFileObjects.DataTempCache;
using Yozeev.Models;
using Yozeev.SystemConfig;
using Yozeev.SystemConfig.Dtos;

namespace Yozeev.Controllers
{
    [Route("api/[Controller]/[Action]")]
    public class FileController : YozeevControllerBase
    {
        private readonly IAppFolder _appFolders;
        private readonly IDataTempFileCacheManager _dataTempFileCacheManager;
        private readonly IHostingEnvironment _hostingEnvironment;
        public FileController(IAppFolder appFolders, IDataTempFileCacheManager dataTempFileCacheManager, IHostingEnvironment hostingEnvironment)
        {
            _appFolders = appFolders;
            _dataTempFileCacheManager = dataTempFileCacheManager;
            _hostingEnvironment = hostingEnvironment;
        }

        [HttpPost]
        [DisableAuditing]
        public ActionResult DownloadFilePathFile(FileDto file)
        {
            var filePath = Path.Combine(_appFolders.TempFileDownloadFolder, file.FileToken);
            if (!System.IO.File.Exists(filePath))
            {
                throw new UserFriendlyException(L("RequestedFileDoesNotExists"));
            }

            var fileBytes = System.IO.File.ReadAllBytes(filePath);
            System.IO.File.Delete(filePath);
            return File(fileBytes, file.FileType, file.FileName);
        }

        [HttpPost]
        [DisableAuditing]
        public ActionResult DownloadTempFile(FileDto file)
        {

         var fileBytes=   _dataTempFileCacheManager.GetFile(file.FileToken);

         if (fileBytes==null)
         {
             return NotFound("当前的文件信息不存在");
         }

         return File(fileBytes, file.FileType, file.FileName);
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PictureResultDto> UploadImageAsync(IFormFile file)
        {
            var fileContent = ContentDispositionHeaderValue.Parse(file.ContentDisposition);

            var fileName = Path.GetFileName(fileContent.FileName.Trim()).ToString();

            var ext = Path.GetExtension(fileName).Replace("\"", "");

            if (!CheckFileType(ext))
            {
                throw new UserFriendlyException(200, "上传的图片格式错误，请上传格式为bmp, jpg, jpeg, png, gif的文件");
            }

            //保存文件
            var dir = Path.Combine(_hostingEnvironment.WebRootPath, "Pictures");

            var newFileName = Guid.NewGuid().ToString() + ext;

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            using (var fileStream = new FileStream(Path.Combine(dir, newFileName), FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }

            return new PictureResultDto { Uri = "Pictures/" + newFileName };
        }

        private bool CheckFileType(string ext)
        {
            string[] allowTypes = { ".bmp", ".jpg", ".jpeg", ".png", ".gif" };
            if (Array.IndexOf(allowTypes, ext.ToLower()) == -1)
            {
                return false;
            }
            return true;
        }

        private bool CheckClientType(string ext)
        {
            string[] allowTypes = { ".exe", ".apk" };
            if (Array.IndexOf(allowTypes, ext.ToLower()) == -1)
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 上传版本文件
        /// </summary>
        /// <param name="file">版本名称_版本代码_版本名称_(d|D)设备类型枚举号_xxx.apk 如：开发版V2手持机_120_v1.2_d4_hnhuyhhnyhnhn_888.apk</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ClientVersionListDto> UploadClientAsync(IFormFile file)
        {
            var fileContent = ContentDispositionHeaderValue.Parse(file.ContentDisposition);

            var fileName = Path.GetFileName(fileContent.FileName.Trim()).ToString();
            var _fileName = fileName.Replace("\"", "");
            var ext = Path.GetExtension(fileName).Replace("\"", "");

            if (!CheckClientType(ext))
            {
                throw new UserFriendlyException(200, "上传的文件格式错误，请上传格式为 exe, apk 的文件");
            }
            //判断文件名是否合法
            //版本名称_版本代码_版本名称_(d|D)设备类型枚举号_xxx.apk
            Regex rx = new Regex(@".+_+([0-9]+)_+(v[0-9]+[.][0-9]+)_+[d|D]([0-9]+)(.+)(apk|exe)");
            MatchCollection matches = rx.Matches(_fileName);
            if (matches.Count != 1 && matches[0].Groups.Count != 6)
            {
                throw new UserFriendlyException(200, "上传的文件格式错误，请上传格式为 exe, apk 的文件");
            }
            ClientVersionListDto clientVersion = new ClientVersionListDto()
            {
                AppName = matches[0].Value,
                VersionCode = matches[0].Groups[1].Value,
                VersionName = matches[0].Groups[2].Value,
                DeviceType = (DeviceTypeEnum)Convert.ToInt32(matches[0].Groups[3].Value),
            };
            //保存文件
            var dir = Path.Combine(_hostingEnvironment.WebRootPath, "ClientVersion");

            var newFileName = _fileName + ext;

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            using (var fileStream = new FileStream(Path.Combine(dir, newFileName), FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }
            return clientVersion;
        }
        List<string> checkRegex(string str)
        {
            List<string> list = new List<string>();
            string text = "1A 2B 3C 4D 5E 6F 7G 8H 9I 10J 11Q 12J 13K 14L 15M 16N ffee80 #800080";
            string strPatten = @"((\d+)([a-z]))\s+";
            Regex rex = new Regex(strPatten, RegexOptions.IgnoreCase);
            MatchCollection matches = rex.Matches(text);
            foreach (Match match in matches)
            {
                GroupCollection groups = match.Groups;
                list.Add(string.Format("<br/>{0} 共有 {1} 个分组：{2}<br/>"
                                            , match.Value, groups.Count, strPatten));
                for (int i = 0; i < groups.Count; i++)
                {
                    list.Add(
                        string.Format("分组 {0} 为 {1}，位置为 {2}，长度为 {3}<br/>"
                                    , i
                                    , groups[i].Value
                                    , groups[i].Index
                                    , groups[i].Length));
                }
            }
            return list;
        }
    }
}


